/**************************************************************************(C)*
 *
 *  This file is part of the GreenHills project
 *  Copyright (C) 2009  Tieto Corporation
 *
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  Not for commmercial use. Only with Tieto permission.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 *************************************************************************(C)*/
#include "mapwiev.h"
#include "ui_mapwiev.h"
#include <QtCore>
#include <QNetworkRequest>
#include <QNetworkReply>
#include <QGraphicsSceneMouseEvent>


using namespace greenhills::client;
using namespace greenhills::gps;

CMapWiev::CMapWiev(QString pKey, QWidget * parent):QWidget(parent),
    m_ui(new Ui::CMapWiev), mManager(new QNetworkAccessManager)
    ,mMath(new CGpsmapViewMathematic(parent))
{
    m_ui->setupUi(this);  
    mScene = new CMapScene(this);
    mScene->setSceneRect(0,0,640,640);
    m_ui->graphicsView->setRenderHints(QPainter::Antialiasing);
    m_ui->graphicsView->setScene(mScene);
    m_ui->graphicsView->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
    m_ui->graphicsView->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
    connect(mScene,SIGNAL(changecoordsOnClick(double,double)),this,SLOT(mouseChangeLabel(double,double)));
    connect(m_ui->pushButton,SIGNAL(clicked()),this,SLOT(firstPaint()));
    connect(m_ui->pushButton_2,SIGNAL(clicked()),this,SLOT(onWayPointCreate()));    
    connect(m_ui->pushButton_4, SIGNAL(clicked()),this,SLOT(onUserLabelCreate()));
    connect(m_ui->pushButton_5, SIGNAL(clicked()),this,SLOT(onChangePosition()));
    connect(mMath,SIGNAL(redrawNeed(QPointF*)),this,SLOT(onMapRedrawNeed(QPointF*)));
    connect(m_ui->lineEdit_3, SIGNAL(textChanged(QString)), this,
                SLOT(onUserHeadingChange(QString)));
    connect(mManager, SIGNAL(finished(QNetworkReply*)),
                this, SLOT(replyFinished(QNetworkReply*)));

    mImgPointer = NULL;
    mLabel = NULL;
    mGroup=NULL;
    mKey=pKey;
    mZmena = false;
    mOldHeading = 0;
}

CMapWiev::~CMapWiev()
{
    delete mManager;
    delete m_ui;
    delete mLabel;
    delete mGroup;
    mGroup = NULL;
    mImgPointer = NULL;
}

void CMapWiev::replyFinished(QNetworkReply *mReply)
{
    if( mImgPointer != NULL ){
        mScene->removeItem(mImgPointer);        
        mImgPointer =NULL;}
        mImg = QImage::fromData(mReply->readAll());
        mImgPointer = mScene->addPixmap(QPixmap::fromImage(mImg));        
    if( mGroup == NULL ){
       mGroup=new QGraphicsItemGroup(mImgPointer,mScene);
       mScene->addItem(mGroup);
      }
    else mGroup->setParentItem(mImgPointer);
    if(!mZmena){
        //QString lat = m_ui->lineEdit->text();
        //QString lon = m_ui->lineEdit_2->text();
        //CGpsmapViewMathematic::myPositionChange(lon,lat);
        mZmena = true;
    }else{
        //QString lat = m_ui->lineEdit->text();
       // QString lon = m_ui->lineEdit_2->text();
//        CGPSPosition pos =
//        CGPSPosition(CGPSLatitude().fromString(lat+"N"),CGPSLongitude().fromString(lon+"E"));
//        mPosun = mMath->evaluateDifference(pos);
        //CGpsmapViewMathematic::myPositionChange(lon,lat);
        moveTargets();
    }
}

void CMapWiev::changeEvent(QEvent * e)
{
     QWidget::changeEvent(e);
    switch (e->type()) {
    case QEvent::LanguageChange:
        m_ui->retranslateUi(this);
        break;
    default:
        break;
    }
}

void CMapWiev::onChangePosition()
{
    QString lat = m_ui->lineEdit->text();
    QString lon = m_ui->lineEdit_2->text();

    CGPSPosition pos =
    CGPSPosition(CGPSLatitude().fromString(lat+"N"),CGPSLongitude().fromString(lon+"E"));
    if(mZmena) mPosun = mMath->evaluateDifference(pos);
    else mZmena=true;
    if( mImgPointer != NULL )mImgPointer->setPos(-mPosun.x(),-mPosun.y());
    CGpsmapViewMathematic::myPositionChange(lon,lat);
}

void CMapWiev::onMapRedrawNeed(QPointF * pPosun = new QPointF(0,0))
{
    QString lat = m_ui->lineEdit->text();
    QString lon = m_ui->lineEdit_2->text();    

    QString gooLat = CGpsmapViewMathematic::toGoogleRepresentation(lat);
    QString gooLon = CGpsmapViewMathematic::toGoogleRepresentation(lon);

    QUrl geoCodeUrl("http://maps.google.com/maps/api/staticmap");
    geoCodeUrl.addQueryItem("center",gooLon + "," +gooLat);
    geoCodeUrl.addQueryItem("zoom", "15");
    geoCodeUrl.addQueryItem("size", "640x640");
    geoCodeUrl.addQueryItem("key",mKey);
    geoCodeUrl.addQueryItem("sensor", "false");
    mPosun.setX(pPosun->x());
    mPosun.setY(pPosun->y());
    CGpsmapViewMathematic::myPositionChange(lon,lat);
    mManager->get( QNetworkRequest(geoCodeUrl) );
}

void CMapWiev::wayPointCreate()
{
    QString lat = m_ui->lineEdit->text();
    QString lon = m_ui->lineEdit_2->text();

    CGPSPosition pos =
    CGPSPosition(CGPSLatitude().fromString(lat+"N"),CGPSLongitude().fromString(lon+"E"));

    QPointF point =  mMath->coordToPixmap(pos);

    CMapLabel * mLabel = new CMapLabel(320+point.x(),320+point.y());    
    mScene->addItem(mLabel);
    mGroup->addToGroup(mLabel);
    mGroup->setZValue(1);
}

void CMapWiev::onWayPointCreate()
{
    wayPointCreate();
}

void CMapWiev::onWayPointDelete()
{
    CMapLabel * lab = selectedTarget();
    mGroup->removeFromGroup(lab);
    mScene->removeItem(lab);
}

CMapLabel * CMapWiev::selectedTarget() const
{
    QList <QGraphicsItem *> items = mScene->selectedItems();    
    if(items.count() == 0 ) return NULL;
    return dynamic_cast<CMapLabel *>(items.first());
}

void CMapWiev::mouseChangeLabel(double x,double y)
{   
    m_ui->label->setText("");
    m_ui->label_2->setText("");   
   QString txt = QString("X:%1").arg(x);
   QString txt1 = QString("Y:%1").arg(y);
   m_ui->label->setText(txt);
   m_ui->label_2->setText(txt1);

}

void CMapWiev::createUserLable()
{
    QString lat = m_ui->lineEdit->text();
    QString lon = m_ui->lineEdit_2->text();
    mLabel = new CUserlabels(320, 320);    
    mLabel->setZValue(2);
    mScene->addItem(mLabel);
}

void CMapWiev::onUserHeadingChange(float pHeading)
{
    float val = pHeading - mOldHeading;
    mOldHeading = pHeading;
    mLabel->translate(315,315);
    mLabel->rotate(val);
    mLabel->translate(-315,-315);    
}

void CMapWiev::onUserHeadingChange(QString heading)
{
    bool ok;
    float hea = heading.toFloat(&ok);
    onUserHeadingChange(hea);
}

void CMapWiev::resizeEvent(QResizeEvent * event)
{    
    if(event->GraphicsSceneResize == QResizeEvent::GraphicsSceneResize){
    resizeRedraw();
    CGpsmapViewMathematic::changeProportions(m_ui->graphicsView->width(),m_ui->graphicsView->height());
 }
}

void CMapWiev::resizeRedraw()
{
    if( mLabel == NULL ){ createUserLable();}
    m_ui->graphicsView->centerOn(320,320);    
}

void CMapWiev::moveTargets()
{    
    if(floor(mPosun.x())!=0.0 && floor(mPosun.y())!=0.0)
    mGroup->setPos(-mPosun.x(),-mPosun.y());
}

void CMapWiev::firstPaint()
{
 onMapRedrawNeed();
}
